package com.zk.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
/**
 * @Auther: tangC
 * @Date: 2020/7/3 14:35
 * @Description:
 */
@Slf4j
public class ZKUtile {

    private static final String host = "60.205.188.230";

    private static final String path = "/root";

    public static void start(){
        run();
    }

    private static void run(){
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(host)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();
        new Thread(()->{
            try {
                TreeCache treeCache = new TreeCache(client, path);
                treeCache.start();
                treeCache.getListenable().addListener(new TreeCacheListener() {
                    @Override
                    public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                        TreeCacheEvent.Type type = event.getType();
                        if (type == TreeCacheEvent.Type.INITIALIZED){
                            System.out.println("zookpeer 第一次初始化完成");
                        }
                        // 节点信息
                        ChildData childData = event.getData();
                        if (childData != null){
                            System.out.println("do someThing");
                            System.out.println(childData.getPath());
                            System.out.println(type);
                        }
                    }
                });
            }catch (Exception e){
                log.error("订阅节点发生错误");
                e.printStackTrace();
            }
        }).start();
    }

    public static void main(String[] args) {
        ZKUtile.start();
        try {
            Thread.sleep(Integer.MAX_VALUE);
        }catch (Exception e){

        }
    }
}